# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'Y08ZOO88882018121710001168': {
        # 云融 支付宝wap 3% 10-3000 loki
        'pay_key': 'a41b24eb5ad14e0a92036518d47613f6',
        'pay_secret': 'bf2d43911783485bada0f3c88d0c1399',
        'gateway': 'https://gateway.wanshangyi.com/scanPay/initPay',
        'query_gateway': 'https://gateway.wanshangyi.com/query/singleOrder',
    },
}


def _get_pay_key(mch_id):
    return APP_CONF[mch_id]['pay_key']


def _get_pay_secret(mch_id):
    return APP_CONF[mch_id]['pay_secret']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _get_pay_type(service):
    #  支付宝wap
    if service == 'alipayw0':  # T0级别
        return '20000203'
    elif service == 'alipayw1':  # T1级别
        return '20000201'
    #  支付宝扫码
    elif service == 'alipays0':
        return '20000303'
    elif service == 'alipays1':
        return '20000301'
    else:
        return '70000203'


def generate_sign(d, pay_secret):
    '''  生成下单签名 '''
    s = 'notifyUrl={}&orderIp={}&orderPrice={}&orderTime={}&outTradeNo={}&payKey={}&productName={}&productType={}&remark={}&returnUrl={}&paySecret={}'.format(
        d['notifyUrl'], d['orderIp'], d['orderPrice'], d['orderTime'], d['outTradeNo'], d['payKey'], d['productName'],
        d['productType'], d['remark'], d['returnUrl'], pay_secret
    )
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_notify_sign(d, pay_secret):
    '''  生成通知签名 '''
    s = ''
    for k in sorted(d.keys()):
        if d[k] != '' and d[k]:
            s += '%s=%s&' % (k, d[k])
    s += 'paySecret=%s' % pay_secret
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_query_sign(d, paySecret):
    '''  生成下单签名 '''
    s = 'outTradeNo={}&payKey={}&paySecret={}'.format(
        d['outTradeNo'], d['payKey'], paySecret
    )
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("yunrongpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def verify_create_response_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("yunrongpay create response sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '103.230.240.174'


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    pay_key = _get_pay_key(app_id)
    pay_secret = _get_pay_secret(app_id)
    service = info.get('service')
    parameter_dict = OrderedDict((
        ('payKey', pay_key),
        ('orderPrice', '%.2f' % pay_amount),
        ('outTradeNo', str(pay.id)),
        ('productType', _get_pay_type(service)),
        ('orderTime', time.strftime("%Y%m%d%H%M%S", time.localtime())),
        ('productName', 'yunrongpay'),
        ('orderIp', _get_device_ip(info)),
        ('returnUrl', '{}/pay/api/{}/yunrongpay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, app_id)),
        ('notifyUrl', '{}/pay/api/{}/yunrongpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('remark', 'charge'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, pay_secret)
    gateway = _get_gateway(app_id)
    _LOGGER.info("yunrongpay create data: %s, order_id is: %s", json.dumps(parameter_dict),
                 parameter_dict['outTradeNo'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(gateway, data=parameter_dict, headers=headers, timeout=3, verify=False)
    _LOGGER.info("yunrongpay create rsp data: %s", response.text)
    pay_message = json.loads(response.text)['payMessage']
    if pay_message.startswith('http'):
        url = pay_message
    else:
        cache_id = redis_cache.save_html(pay.id, pay_message)
        url = settings.PAY_CACHE_URL + cache_id
    return {'charge_info': url}


# SUCCESS
def check_notify_sign(request, app_id):
    data = dict(request.GET.iteritems())
    _LOGGER.info("yunrongpay notify data: %s, order_id is: %s", json.dumps(data), data['outTradeNo'])
    pay_secret = _get_pay_secret(app_id)
    verify_notify_sign(data, pay_secret)
    pay_id = data['outTradeNo']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('yunrongpay event does not contain pay ID')

    pay = order_db.get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['tradeStatus'])
    trade_no = data['trxNo']
    total_fee = float(data['orderPrice'])

    discount = float(json.loads(pay.extend or '{}').get('discount', 0))
    extend = {
        'discount': discount,
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 'SUCCESS' or trade_status == 'FINISH':
        _LOGGER.info('yunrongpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    pay_key = _get_pay_key(app_id)
    pay_secret = _get_pay_secret(app_id)
    parameter_dict = OrderedDict((
        ('payKey', pay_key),
        ('outTradeNo', str(pay_id)),
    ))
    parameter_dict['sign'] = generate_query_sign(parameter_dict, pay_secret)
    _LOGGER.info("yunrongpay query  data: %s, order_id is: %s", parameter_dict, parameter_dict['outTradeNo'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3, verify=False)
    _LOGGER.info("yunrongpay query  rsp data: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = str(data['orderStatus'])
        trade_no = data['trxNo']
        total_fee = float(data['orderPrice'])
        discount = float(json.loads(pay_order.extend or '{}').get('discount', 0))

        extend = {
            'discount': discount,
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == 'SUCCESS' or trade_status == 'FINISH':
            _LOGGER.info('yunrongpay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('yunrongpay data error, status_code: %s', response.status_code)
